package cn.kmust.booth.portal.controller;

import cn.kmust.booth.portal.service.ISendSms;
import cn.kmust.booth.portal.service.ex.SmsException;
import cn.kmust.booth.portal.vo.R;
import com.aliyuncs.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author XChao
 * @date 2020/8/9 - 14:37
 */
@Controller
public class SmsApiController {

    @Autowired
    private ISendSms sendSms;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //http://localhost:8080/send?phone=15559770917
    @GetMapping("/send")
    @ResponseBody
    public R<Void> code(String phone){
        //调用发送方法
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok(phone + ":" + code + "已存在,还没有过期");
        }

        code = UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param = new HashMap<>();
        param.put("code",code);

        Boolean isSend = sendSms.sendSms(phone,"SMS_195723403",param);

        if (isSend) {
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok(phone + ":" + code + "发送成功");
        }else {
            throw new SmsException("服务器繁忙,请稍后再试!");
        }
    }
}
